<script setup>
// 引入 api
import { ref } from "vue"

// 商品列表
const goods = ref([
    {
        image: "src/assets/images/20250427103349.png",
        name: "IPhone 10",
        price: 2999.99,
        stock: 10,
        className: {
            'in-stock': true,
            'out-of-stock': false
        }
    },
    {
        image: "src/assets/images/20250427103349.png",
        name: "IPhone 11",
        price: 3999.99,
        stock: 5,
        className: {
            'in-stock': true,
            'out-of-stock': false
        }
    }
    ,
    {
        image: "src/assets/images/20250427103349.png",
        name: "IPhone 12",
        price: 4999.99,
        stock: 2,
        className: {
            'in-stock': true,
            'out-of-stock': false
        }
    }
])

// 点击按钮
function btn(index) {
    goods.value[index].stock > 0 ? goods.value[index].stock-- : alert("暂无库存")

    if (goods.value[index].stock === 0) {
        goods.value[index].className["in-stock"] = false
        goods.value[index].className["out-of-stock"] = true
    }
}

</script>

<template>
    <!-- 商品列表 -->
    <table>
        <thead>
            <tr>
                <th>图片</th>
                <th>商品名称</th>
                <th>价格</th>
                <th>库存</th>
                <th>操作</th>
            </tr>
        </thead>

        <tbody>

            <tr v-for="(good, index) in goods">
                <td><img :src="good.image" /></td>
                <td>
                    <p>{{ good.name }}</p>
                </td>
                <td><span>{{ good.price }}￥</span></td>
                <td><span>{{ good.stock }}</span></td>
                <td><input type="button" value="购买" @click="btn(index)" :class="good.className"></td>
            </tr>
        </tbody>
    </table>
</template>

<style>
.in-stock {
    background-color: #00ff00;
}

.out-of-stock {
    background-color: #ff0000;
}
</style>